package com.atguigu.influxdb.jmx.insert.util;

import com.atguigu.influxdb.util.InfluxDBConnection;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * JMX插入的工具类
 *
 * @Author 剧情再美终是戏
 * @Date 2019/12/27
 * @return
 * @Version 1.0
 **/
public class JmxInsertUtil {

    private static Logger logger = Logger.getLogger(JmxInsertUtil.class);


    /**
     * 插入
     *
     * @param jmxId  监控实例的id
     * @param jmxUrl 监控实例的jmx响应结果url
     * @return void
     * @Author 剧情再美终是戏
     * @Date 2019/12/27
     * @Version 1.0
     **/
    public static void insert(String operUrl, String jmxId, String jmxUrl) {

        // 根据监控实例的jmx响应结果url获取结果
        String jmxResponse = getJmxResponse(jmxUrl);
        logger.debug("com.atguigu.influxdb.jmx.insert.util.JmxInsertUtil.getJmxResponse method response : " + jmxResponse);

        // 将结果写入influxDB中
        insertDB(operUrl, jmxId, jmxResponse);
    }

    public static void insertDB(String operUrl, String jmxId, String jmxResponse) {
        if (null == jmxResponse || jmxResponse.trim().length() == 0) {
            logger.error("com.atguigu.influxdb.jmx.insert.util.JmxInsertUtil.insertDB happen error : jmxResponse is null");
            return;
        }
        InfluxDBConnection influxDBConnection = null;
        try {
            // 获取连接
            influxDBConnection =
                    new InfluxDBConnection("root", "root", operUrl, "mydb", null);
            if (null == influxDBConnection) {
                logger.error("com.atguigu.influxdb.jmx.insert.util.JmxInsertUtil.insertDB happen error : influxDBConnection is null");
                return;
            }
            // 时间处理
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
            long currentTime = System.currentTimeMillis();

            // Map<String, String> tags 以jmxid和时间(yyy-MM-dd hh)为索引
            Map<String, String> tags = new HashMap<>();
            tags.put("jmxid", jmxId);
            tags.put("hour", dateFormat.format(new Date(currentTime)));

            // Map<String, Object> fields
            Map<String, Object> fields = new HashMap<>();
            fields.put("value", jmxResponse);
            influxDBConnection.insert("f33", tags, fields, currentTime, TimeUnit.NANOSECONDS);
        } catch (Exception e) {
            logger.error("com.atguigu.influxdb.jmx.insert.util.JmxInsertUtil.insertDB happen error : " + e);
        } finally {
            if (null != influxDBConnection) {
                influxDBConnection.close();
            }
        }
    }


    /**
     * 获取JMX的请求内容
     *
     * @param jmxUrl
     * @return java.lang.String
     * @Author 剧情再美终是戏
     * @Date 2019/12/27
     * @Version 1.0
     **/
    public static String getJmxResponse(String jmxUrl) {
        // 定义返回结果
        String result = "";

        // 创建Httpclient对象,相当于打开了浏览器
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 创建HttpGet请求，相当于在浏览器输入地址
        HttpGet httpGet = new HttpGet(jmxUrl);

        CloseableHttpResponse response = null;
        try {
            // 执行请求，相当于敲完地址后按下回车。获取响应
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析响应，获取数据
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            logger.error("com.atguigu.influxdb.jmx.insert.util.JmxInsertUtil.getJmxResponse happen error : " + e);
        } finally {
            try {
                if (response != null) {
                    // 关闭资源
                    response.close();
                }
                // 关闭浏览器
                httpclient.close();
            } catch (IOException e) {
                logger.error("com.atguigu.influxdb.jmx.insert.util.JmxInsertUtil.getJmxResponse  happen error : " + e);
            }
        }
        return result;
    }

    // 查询数据方法sql: select * from f33 where hour='2019-12-27 16' and jmxid='hadoop103-f3' order by time desc
    public static void main(String[] args) {
        // 测试方法
//        insert("http://hadoop103:8086", "hadoop103-f3", "http://hadoop103:1234/metrics");

        // 生产方法
        if (null == args || args.length < 3) {
            logger.error("com.atguigu.influxdb.jmx.insert.util.JmxInsertUtil.main param error : args is must, param list: opUrl, jmxId, jmxUrl");
            return;
        }
        insert(args[0], args[1], args[2]);
        logger.info("com.atguigu.influxdb.jmx.insert.util.JmxInsertUtil.main insert success!");
    }
}
